<template>
  <div class="dashboard">
    <h2 class="dashboard-title">情报数据查询</h2>
    <el-row class="dashboard-row" gutter="20">
      <!-- 左侧图表 -->
      <el-col :span="8" class="left-column">
        <el-row class="full-width">
          <el-col :span="12">
            <el-card class="chart-card">
              <h3 class="chart-title">关键字热词</h3>
              <div
                ref="wordCloudChart"
                id="my_canvas"
                class="chart-container-large"
              ></div>
            </el-card>
          </el-col>
          <el-col :span="12">
            <el-card class="chart-card">
              <h3 class="chart-title">数据来源</h3>
              <div
                ref="pieChart"
                id="my_pieChart"
                class="chart-container-small"
              ></div>
            </el-card>
            <el-card class="chart-card" style="margin-top: 20px">
              <h3 class="chart-title">文件类型</h3>
              <div
                ref="radarChart"
                id="my_radarChart"
                class="chart-container-small"
              ></div>
            </el-card>
          </el-col>
        </el-row>

        <el-card class="chart-card full-width" style="margin-top: 20px">
          <h3 class="chart-title">情报上传时间统计</h3>
          <div
            ref="timeSeriesChart"
            id="my_timeSeriesChart"
            class="chart-container-large"
          ></div>
        </el-card>
      </el-col>
      <el-col :span="16" class="right-column">
        <el-card class="filter-card">
          <ScreenColumn @button-clicked="handleButtonClick"/>

          <h3>热门搜索词</h3>
          <div class="hot-words">
            <el-tag>当前内容</el-tag>
            <el-tag>数据来源</el-tag>
            <el-tag>当前内容</el-tag>
            <el-tag>数据来源</el-tag>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from "vue";

import * as echarts from "echarts";
import * as WordCloud from "wordcloud";
import ScreenColumn from "./ScreenColumn.vue";
import { useRouter } from "vue-router";
// ————————————————————————————————————————————————————————————————————————
const router = useRouter();
const list = ref([
  {
    value: "50",
    name: "华为",
    textStyle: {
      shadowBlur: 4,
      shadowColor: "#ECEFFF",
      shadowOffsetY: 14,
      color: "#73DDFF",
    },
  }, // 50
  { value: "30", name: "VIVO" },
  { value: "29", name: "OPPO" },
  { value: "28", name: "HONOR" },
  { value: "27", name: "红米" },
  { value: "26", name: "小米" },
  { value: "25", name: "美图" },
  { value: "24", name: "ONEPLUS" },
  { value: "23", name: "魅族" },
  { value: "22", name: "红手指" },
  { value: "21", name: "SAMSUNG" },
  { value: "20", name: "金立" },
  { value: "16", name: "BLACKBERRY" },
  { value: "15", name: "诺基亚" },
  { value: "14", name: "锤子" },
  { value: "13", name: "大疆" },
  { value: "12", name: "361" },
  { value: "11", name: "摩托罗拉" },
  { value: "10", name: "联想" },
  { value: "9", name: "玩家国度" },
]);
const wordCloudOption = ref({
  tooltip: {
    show: true,
    borderColor: "#fe9a8bb3",
    borderWidth: 1,
    padding: [10, 15, 10, 15],
    confine: true,
    backgroundColor: "rgba(255, 255, 255, .9)",
    textStyle: {
      color: "hotpink",
      lineHeight: 22,
    },
    extraCssText:
      "box-shadow: 0 4px 20px -4px rgba(199, 206, 215, .7);border-radius: 4px;",
  },
  series: [
    {
      type: "wordCloud",
      // The shape of the "cloud" to draw. Can be any polar equation represented as a
      // callback function, or a keyword present. Available presents are circle (default),
      // cardioid (apple or heart shape curve, the most known polar equation), diamond (
      // alias of square), triangle-forward, triangle, (alias of triangle-upright, pentagon, and star.

      shape: "pentagon",

      // A silhouette image which the white area will be excluded from drawing texts.
      // The shape option will continue to apply as the shape of the cloud to grow.

      // Folllowing left/top/width/height/right/bottom are used for positioning the word cloud
      // Default to be put in the center and has 75% x 80% size.

      left: "center",
      top: "center",
      width: "100%",
      height: "100%",
      right: null,
      bottom: null,

      // Text size range which the value in data will be mapped to.
      // Default to have minimum 12px and maximum 60px size.

      sizeRange: [14, 50],

      // Text rotation range and step in degree. Text will be rotated randomly in range [-90, 90] by rotationStep 45

      rotationRange: [0, 0],
      rotationStep: 0,

      // size of the grid in pixels for marking the availability of the canvas
      // the larger the grid size, the bigger the gap between words.

      gridSize: 25,

      // set to true to allow word being draw partly outside of the canvas.
      // Allow word bigger than the size of the canvas to be drawn
      drawOutOfBound: false,

      // If perform layout animation.
      // NOTE disable it will lead to UI blocking when there is lots of words.
      layoutAnimation: true,

      // Global text style
      textStyle: {
        fontFamily: "PingFangSC-Semibold",
        fontWeight: 600,
        color: function (params) {
          let colors = [
            "#fe9a8bb3",
            "#fe9a8bb3",
            "#fe9a8b03",
            "#9E87FFb3",
            "#9E87FFb3",
            "#9E87FFb3",
            "#fe9a8bb3",
            "#fe9a8bb3",
            "#fe9a8bb3",
            "#73DDFF",
            "#58D5FF",
          ];
          return colors[parseInt(Math.random() * 10)];
        },
      },
      emphasis: {
        focus: "none",
      },

      // Data is an array. Each array item must have name and value property.
      data: list,
    },
  ],
});
// 数据来源————饼图
const pieChartOption = ref({
  title: {
    text: "80",
    subtext: "总平均值(分)111",
    x: "center",
    y: "center",
    textStyle: {
      fontSize: 30,
      fontWeight: "normal",
      color: ["#333"],
    },
    subtextStyle: {
      color: "#666",
      fontSize: 16,
    },
  },
  tooltip: {
    trigger: "item",
  },
  // legend: {
  //   top: '5%',
  //   left: 'center'
  // },
  series: [
    {
      name: "Access From",
      type: "pie",
      radius: ["40%", "70%"],
      avoidLabelOverlap: false,
      itemStyle: {
        borderRadius: 10,
        borderColor: "#fff",
        borderWidth: 2,
      },
      label: {
        show: false,
        position: "center",
      },
      emphasis: {
        label: {
          show: true,
          fontSize: 40,
          fontWeight: "bold",
        },
      },
      labelLine: {
        show: false,
      },
      data: [
        { value: 1048, name: "Search Engine" },
        { value: 735, name: "Direct" },
        { value: 580, name: "Email" },
        { value: 484, name: "Union Ads" },
        { value: 300, name: "Video Ads" },
      ],
    },
  ],
});
// 文件类型————雷达图
const radarChartOption = ref({
  color: ["#67F9D8", "#FFE434", "#56A3F1", "#FF917C"],
  title: {
    text: "Customized Radar Chart",
  },
  legend: {},
  radar: [
    {
      // 保留第二个雷达图的样式配置
      indicator: [
        { text: "Indicator1", max: 150 },
        { text: "Indicator2", max: 150 },
        { text: "Indicator3", max: 150 },
        { text: "Indicator4", max: 120 },
        { text: "Indicator5", max: 108 },
        { text: "Indicator6", max: 72 },
      ],
      center: ["50%", "50%"], // 居中显示
      radius: 120,
      axisName: {
        color: "#fff",
        backgroundColor: "#666",
        borderRadius: 3,
        padding: [3, 5],
      },
    },
  ],
  series: [
    {
      type: "radar",
      radarIndex: 0, // 关联到唯一的雷达图
      data: [
        {
          value: [120, 118, 130, 100, 99, 70],
          name: "Data C",
          symbol: "rect",
          symbolSize: 12,
          lineStyle: {
            type: "dashed",
          },
          label: {
            show: true,
            formatter: function (params) {
              return params.value;
            },
          },
        },
        {
          value: [100, 93, 50, 90, 70, 60],
          name: "Data D",
          areaStyle: {
            color: new echarts.graphic.RadialGradient(0.1, 0.6, 1, [
              {
                color: "rgba(255, 145, 124, 0.1)",
                offset: 0,
              },
              {
                color: "rgba(255, 145, 124, 0.9)",
                offset: 1,
              },
            ]),
          },
        },
      ],
    },
  ],
});
// 时间统计————凹凸图
const names = [
  "Orange",
  "Tomato",
  "Apple",
  "Sakana",
  "Banana",
  "Iwashi",
  "Snappy Fish",
  "Lemon",
  "Pasta",
];
const years = ["2001", "2002", "2003", "2004", "2005", "2006"];
const shuffle = (array) => {
  let currentIndex = array.length;
  let randomIndex = 0;
  while (currentIndex > 0) {
    randomIndex = Math.floor(Math.random() * currentIndex);
    currentIndex--;
    [array[currentIndex], array[randomIndex]] = [
      array[randomIndex],
      array[currentIndex],
    ];
  }
  return array;
};
const generateRankingData = () => {
  const map = new Map();
  const defaultRanking = Array.from({ length: names.length }, (_, i) => i + 1);
  for (const _ of years) {
    const shuffleArray = shuffle(defaultRanking);
    names.forEach((name, i) => {
      map.set(name, (map.get(name) || []).concat(shuffleArray[i]));
    });
  }
  return map;
};
const generateSeriesList = () => {
  const seriesList = [];
  const rankingMap = generateRankingData();
  rankingMap.forEach((data, name) => {
    const series = {
      name,
      symbolSize: 20,
      type: "line",
      smooth: true,
      emphasis: {
        focus: "series",
      },
      endLabel: {
        show: true,
        formatter: "{a}",
        distance: 20,
      },
      lineStyle: {
        width: 4,
      },
      data,
    };
    seriesList.push(series);
  });
  return seriesList;
};
const timeSeriesChartOption = ref({
  title: {
    text: "Bump Chart (Ranking)",
  },
  tooltip: {
    trigger: "item",
  },
  grid: {
    left: 30,
    right: 110,
    bottom: 30,
    containLabel: true,
  },
  toolbox: {
    feature: {
      saveAsImage: {},
    },
  },
  xAxis: {
    type: "category",
    splitLine: {
      show: true,
    },
    axisLabel: {
      margin: 30,
      fontSize: 16,
    },
    boundaryGap: false,
    data: years,
  },
  yAxis: {
    type: "value",
    axisLabel: {
      margin: 30,
      fontSize: 16,
      formatter: "#{value}",
    },
    inverse: true,
    interval: 1,
    min: 1,
    max: names.length,
  },
  series: generateSeriesList(),
});
// ————————————————————————————————————————————————————————————————————————
const handleButtonClick = ()=>{
  // 子组件按钮触发
  router.push('/about')
}
// 定义图表的 ref
const chartRefs: any = {
  wordCloudChart: ref(null),
  pieChart: ref(null),
  radarChart: ref(null),
  timeSeriesChart: ref(null),
};

// 初始化图表函数
const initChart = (key: string, chartRef: any) => {
  if (!chartRef.value) return;
  // debugger
  switch (key) {
    case "pieChart":
      const pieChartInstance = echarts.init(chartRef.value);
      pieChartInstance.setOption(pieChartOption.value);
      break;
    case "radarChart":
      const radarChartInstance = echarts.init(chartRef.value);
      radarChartInstance.setOption(radarChartOption.value);
      break;
    case "timeSeriesChart":
      const timeSeriesChartInstance = echarts.init(chartRef.value);
      timeSeriesChartInstance.setOption(timeSeriesChartOption.value);
      break;
    default:
      break;
  }
};

// 初始化词云图
const initWordCloud = () => {
  const canvas = chartRefs.wordCloudChart.value;
  if (!canvas) {
    chartRefs.wordCloudChart.value = document.getElementById("my_canvas");
    // const chartInstance = echarts.init(document.getElementById('my_canvas'))
    // chartInstance.setOption({
    //   // 图表配置
    //   ...option.value
    // })
    WordCloud.default(chartRefs.wordCloudChart.value, {
      list: [
        ["foo", 12],
        ["bar", 6],
        ["bar", 6],
        ["bar", 6],
        ["bar", 6],
        ["bar", 6],
        ["bar", 6],
      ],
    });
  }
};
// 组件挂载时初始化图表
onMounted(() => {
  chartRefs.pieChart.value = document.getElementById("my_pieChart");
  chartRefs.radarChart.value = document.getElementById("my_radarChart");
  chartRefs.timeSeriesChart.value =
    document.getElementById("my_timeSeriesChart");
  // 遍历 chartRefs 对象中的所有值，并对每个值调用 initChart 函数。
  Object.entries(chartRefs).forEach(([key, value]) => initChart(key, value));
  // 初始化词云图
  initWordCloud();
});
</script>

<style lang="scss" scoped>
.dashboard {
  padding: 20px;
}

.dashboard-row {
  display: flex;
  align-items: stretch;
}

.left-column {
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
}

.chart-card {
  margin-bottom: 20px;
}

.chart-container-large {
  height: 300px; /* 调整大图表高度 */
}

.chart-container-small {
  height: 150px; /* 调整小图表高度 */
}

.right-column {
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
}

.filter-card {
  flex-grow: 1;
  padding: 20px;
  height: 100%;
}
</style>
